#!/bin/bash

echo "=== RISC-V Compiler Test Script ==="
echo

# 检查依赖
echo "1. Checking dependencies..."
if ! command -v bison &> /dev/null; then
    echo "ERROR: bison not found. Please install bison."
    exit 1
fi

if ! command -v flex &> /dev/null; then
    echo "ERROR: flex not found. Please install flex."
    exit 1
fi

if ! command -v g++ &> /dev/null; then
    echo "ERROR: g++ not found. Please install g++."
    exit 1
fi

echo "✓ All dependencies found"
echo

# 清理之前的构建
echo "2. Cleaning previous build..."
make clean
echo "✓ Clean completed"
echo

# 编译编译器
echo "3. Building compiler..."
make all
if [ $? -ne 0 ]; then
    echo "ERROR: Compilation failed"
    exit 1
fi
echo "✓ Compiler built successfully"
echo

# 测试简单程序
echo "4. Testing simple program (test.c)..."
./compiler test.c
if [ $? -ne 0 ]; then
    echo "ERROR: Simple test failed"
    exit 1
fi
echo "✓ Simple test completed"
echo

# 检查生成的汇编文件
if [ -f "test.s" ]; then
    echo "✓ Assembly file generated: test.s"
    echo "First 10 lines of generated assembly:"
    head -10 test.s
    echo
else
    echo "WARNING: Assembly file not generated"
fi

# 测试复杂程序
echo "5. Testing complex program (test_complex.c)..."
./compiler test_complex.c
if [ $? -ne 0 ]; then
    echo "ERROR: Complex test failed"
    exit 1
fi
echo "✓ Complex test completed"
echo

# 检查生成的汇编文件
if [ -f "test_complex.s" ]; then
    echo "✓ Assembly file generated: test_complex.s"
    echo "First 10 lines of generated assembly:"
    head -10 test_complex.s
    echo
else
    echo "WARNING: Assembly file not generated"
fi

# 显示文件大小
echo "6. Generated files:"
ls -la *.s 2>/dev/null || echo "No .s files found"

echo
echo "=== Test completed successfully! ==="
echo
echo "To run the generated assembly code:"
echo "1. Install RISC-V toolchain:"
echo "   brew install riscv-gnu-toolchain"
echo
echo "2. Compile the assembly:"
echo "   riscv64-unknown-elf-gcc -o test_program test.s"
echo
echo "3. Run with QEMU:"
echo "   qemu-riscv64 test_program" 